﻿using Microsoft.EntityFrameworkCore;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace EfCore
{
    internal class Program
    {
        static  void Main(string[] args)
        {
            using(SqlDbContext db = new SqlDbContext())
            {

                // 添加
               // await Add(db);

                // 修改
                Update(db);

                // 查找
                var person = db.Persons.FirstOrDefault(p=>p.Name =="lyf");
                Console.WriteLine(person?.Name);
                // 分组查找
                var listVal = db.subjects.GroupBy(p => p.StudentName).Select(p => new { Student = p.Key, MaxScore = p.Max(p=>p.Score), AvergeScore=p.Average(p=>p.Score) });
                foreach(var item in listVal)
                {
                    Console.WriteLine(item.Student+"-"+item.MaxScore+"-"+item.AvergeScore);
                }

                // 删除
                 db.Persons.Where(p => p.Name == "eric").ExecuteDelete();
                 db.SaveChanges();
                Console.ReadKey();
            }
        }

        // 添加
        public static  void Add(SqlDbContext db)
        {
            db.Persons.Add(new Entity.Stuent()
            {
                Name = "eric",
                Age = 18,
                Address = "yingCaiRoad"
            });

            db.Persons.Add(new Entity.Stuent()
            {
                Name = "lyf",
                Age = 22,
                Address = "yingCaiRoad"
            });

            db.subjects.Add(new Entity.Subject() { Score = 88, SubjectName = "c#", StudentName = "eric" });
            db.subjects.Add(new Entity.Subject() { Score = 99, SubjectName = "java", StudentName = "eric" });
            db.subjects.Add(new Entity.Subject() { Score = 77, SubjectName = "c++", StudentName = "eric" });
            db.subjects.Add(new Entity.Subject() { Score = 90, SubjectName = "c#", StudentName = "lyf" });
            db.subjects.Add(new Entity.Subject() { Score = 88, SubjectName = "java", StudentName = "lyf" });
            db.subjects.Add(new Entity.Subject() { Score = 79, SubjectName = "C++", StudentName = "lyf" });
            db.SaveChanges();
        }

        public static  void  Update(SqlDbContext db)
        {
            var subjects = db.subjects.Where(p => p.SubjectName == "c#");
            foreach (var item in subjects)
            {
                item.Score += 2;
            }

           db.SaveChanges();
        }
    }
}